package com.gitee.kamismile.gatewayWeb.component.handler;

import com.gitee.kamismile.gatewayWeb.component.common.APPWSChannel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelId;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by win7 on 2016/10/30.
 */
public class HeartBeatHandler extends ChannelDuplexHandler {
    protected final Logger logger = LoggerFactory.getLogger(getClass());


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (!(evt instanceof IdleStateEvent)){
            super.userEventTriggered(ctx, evt);
            return;
        }
        if (evt instanceof IdleStateEvent) {
//            Message.RouterMessage.Builder msg = Message.RouterMessage.newBuilder();
//
//            Message.RouterResponse.Builder resp = Message.RouterResponse.newBuilder();
//            resp.setSeq(0L);
//            resp.setRouter(gatewayAgentConstant.getRouter());
//            Message.Command.Builder cmd = Message.Command.newBuilder();
//            cmd.setCommand("server@connect@heart");
//            resp.setCmd(cmd);
//
//            Message.Result.Builder result = Message.Result.newBuilder();
//            result.setCode(0);
//            resp.setResult(result);
//
//            msg.addResponse(resp);
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
//                logger.info("[发送心跳探测消息READER_IDLE]");
//                ctx.writeAndFlush(msg);
            } else if (e.state() == IdleState.WRITER_IDLE) {
//                logger.info("[发送心跳探测消息WRITER_IDLE]");
//                ctx.writeAndFlush(msg);
            } else if (e.state() == IdleState.ALL_IDLE) {
//                logger.info("[发送心跳探测消息ALL_IDLE]");
//                ctx.writeAndFlush(msg);
//                String token = APPWSChannel.channelTokens.remove(ctx.channel().id().asLongText());
//                if(StringUtils.isNotBlank(token)){
//                    APPWSChannel.tokenChannels.remove(token);
//                }
//                APPWSChannel.channels.remove(ctx.channel());
//                APPWSChannel.channelsText.remove(ctx.channel().id().asLongText());
                ctx.channel().close();

            }
        }
    }


}
